<template>
  <div class="edit-cont">
    <!-- 地址输入区 -->
    <div class="input-wrapper">
      <van-field v-model="address.receiver" :label="t('addressSelect_consignee_key')" :placeholder="t('addressSelect_consignee_name')" maxlength="15" />
      <div class="phone-cont" :class="[{ 'error-phone': showPhoneError }]">
        <div class="phone-left">
          <span class="phone-title">{{ t('addressSelect_mobile_phone') }}</span>
        </div>
        <!-- 区号 -->
        <area-code :currentArea="currentArea" @changeArea="changeArea"></area-code>
        <div class="phone-detail">
          <van-field v-model="address.phone" class="phone-text" :placeholder="t('addressSelect_consignee_phone')" type="tel" :formatter="limitInput"
            @blur="phoneBlur" />
        </div>
        <div class="phone-obtain" @click="obtainPhone(true)" v-if="showObtain">{{ t('obtain_phone') }}</div>
      </div>
      <van-field v-model="address.area" :label="t('addressSelect_area')" :placeholder="t('addressSelect_select_address')" :class="{ invalid: invalidAddress }" readonly
        @click="showArea = true">
        <i class="iconfont icon-zhixiang" slot="right-icon"></i>
      </van-field>
      <div class="address-detail">
        <van-field v-model="address.detail" :label="t('addressSelect_detailed_address')" :placeholder="t('addressSelect_street_house')" maxlength="120" type="textarea"
          autosize />
        <div class="detail-error" v-show="showDetailError">{{ t('addressSelect_characters') }}</div>
      </div>
    </div>
    <!-- 默认收货地址开关组件 -->
    <div class="default-wrapper">
      <div>{{ t('addressSelect_set_default_address') }}</div>
      <van-switch v-model="isdefault" :class="{ 'theme-customize-bg': isdefault }" size="24px" />
    </div>
    <!-- 底部操作按钮 -->
    <div class="finish-btn"  v-fixIosBottom="{ paddingBottom: '0.50rem' }">
      <div class="finish-btn-wrapper">
        <div v-if="isNew" class="finish theme-customize-bg" @click="saveAddress()"
          :class="{ disabled: !saveButtonEnabled }">
          {{ !haveAddress ? t('save_and_use') : t('save') }}
        </div>
        <div class="finish-double" v-else>
          <div class="cancel-btn" @click="deleteAddress">{{ t('delete') }}</div>
          <div class="finish2 theme-customize-bg" @click="saveAddress()" :class="{ disabled: !saveButtonEnabled }">
            {{ t('addressSelect_save_address') }}
          </div>
        </div>
      </div>
    </div>
    <!-- 地址选择器 -->
    <van-popup v-model="showArea" position="bottom" :overlay="true" style="height: 70%">
      <van-cascader v-model="addressValue" :title="t('addressSelect_select_area')" :options="areaList" @close="showArea = false"
        @finish="onConfirmArea" />
      <div class="safe-area-inset-bottom"></div>
    </van-popup>
  </div>
</template>

<script>
import { Switch, Cascader, Dialog, Toast, Field } from "vant";
import { getGoodsAddressDetail, getGoodsRegion, obtainPhone, addressAdd, addressEdit, addressDelete } from '../../fetch-data';
import areaCode from "../areaCode";
import { ADDRESS_HANDLE } from "../../utils/constants";
import locale from '../../../../mixins/locale'

export default {
  name: 'AddressEdit',
  mixins: [locale],
  props: {
    selectAddressId: {
      // eslint-disable-next-line vue/require-prop-type-constructor
      type: String | Number,
      default: ''
    },
    haveAddress: {
      type: Boolean,
      default: false
    },
    addressInfo: {
      typeof: Object,
      default: () => ({})
    },
  },
  data() {
    return {
      // 展示地址选择器、地址列表等
      showArea: false,
      isdefault: false, // 是否默认收货地址
      // 客户信息等
      address: {
        receiver: "",
        phone: "",
        area: "",
        detail: "",
        province: "",
        city: "",
        county: "",
      },
      addressValue: "",
      cityList: [],
      addressChanged: false,
      areaList: [],
      saveButtonEnabled: true, // 避免接口返回前多次按下按钮
      currentArea: {
        nation_name: "中国",
        nation_code: "86",
      },
      showPhoneError: false,
      showDetailError: false,
      userInfo: {},
    };
  },
  components: {
    [Switch.name]: Switch,
    [Cascader.name]: Cascader,
    [Dialog.name]: Dialog,
    areaCode,
    [Field.name]: Field,
  },
  mounted() {
    this.selectAddressId && this.getGoodsAddressDetail(this.selectAddressId);
    this.getGoodsRegion();
    this.isNew && this.obtainPhone(false);
  },
  computed: {
    addressDetailCount() {
      return this.address.detail;
    },
    // 用于正则校验每个输入框的数组
    dataArray() {
      let arr = [];
      for (const item in this.address) {
        arr.push({
          key: item,
          value: this.address[item],
        });
      }
      return arr;
    },
    invalidAddress() {
      return (
        this.address.calculate_freight === false &&
        this.address.calculate_freight_text ===
        this.t('addressSelect_area_updated_re-edit') &&
        !this.addressChanged
      );
    },
    //用于标示进入编辑页时是新增（new）/编辑（edit）
    isNew() {
      return !this.selectAddressId;
    },
    // 是否展示填充手机号
    showObtain() {
      return this.isNew && this.userInfo.phone
    }
  },
  methods: {
    // 编辑时获取地址详情回填
    getGoodsAddressDetail(address_id) {
      const params = {
        address_id
      }
      getGoodsAddressDetail(params).then(res => {
        let { province, city, county } = res;
        this.address = res;
        this.address.area =
          `${province}` +
          (city ? `/${city}` : "") +
          (county ? `/${county}` : "");
        this.isdefault = res.is_default == 1;
        res.currentArea && res.currentArea.nation_code && (this.currentArea = res.currentArea);
      })
    },
    // 获取收货地址省市区
    getGoodsRegion() {
      getGoodsRegion().then(res => {
        this.cityList = res;
        this.handleAreaList();
      })
    },
    // 处理省市区数据格式
    handleAreaList() {
      this.areaList = this.cityList.map((province) => {
        let newProvince = {};
        newProvince.text = province.name;
        newProvince.value = province.region_id;

        if (this.address.province === province.name) {
          this.addressValue = province.region_id;
        }

        if (province.cities.length) {
          newProvince.children = province.cities.map(
            (city) => {
              let newCity = {};
              newCity.text = city.name;
              newCity.value = city.region_id;

              if (
                this.address.province ===
                province.name &&
                this.address.city === city.name
              ) {
                this.addressValue = city.region_id;
              }

              newCity.children = city.counties.map(
                (county) => {
                  let newCounty = {};
                  newCounty.text = county.name;
                  newCounty.value = county.region_id;

                  if (
                    this.address.province ===
                    province.name &&
                    this.address.city ===
                    city.name &&
                    this.address.county ===
                    county.name
                  ) {
                    this.addressValue =
                      county.region_id;
                  }

                  return newCounty;
                }
              );

              return newCity;
            }
          );
        }

        return newProvince;
      });
    },
    // 填充手机号
    obtainPhone(bool) {
      obtainPhone().then(res => {
        this.userInfo = res;
        if (bool) {
          this.address.phone = res.phone;
          if (res.phone) {
            this.phoneBlur();
            Toast(this.t('auto_fill_tip'))
          }
        }
      })
    },
    // 选择区号弹框显隐
    changeArea(item) {
      this.currentArea = item;
    },
    // 手机号失焦校验
    phoneBlur() {
      const patt = /^[1][3-9][\d]{9}/.test(this.address.phone);
      if (this.currentArea.nation_code === '86' && (this.address.phone.length != 11 || !patt)) {
        this.showPhoneError = true;
        Toast(this.t('address_phone_num'))
      } else {
        this.showPhoneError = false;
      }
    },
    // 确认选择地址事件
    onConfirmArea({ selectedOptions }) {
      this.showArea = false;
      this.address.province = selectedOptions[0].text;
      this.address.city = selectedOptions[1]
        ? selectedOptions[1].text
        : "";
      this.address.county = selectedOptions[2]
        ? selectedOptions[2].text
        : "";
      this.address.area = selectedOptions
        .map((option) => option.text)
        .join("/");
      this.showArea = false;
      this.addressChanged = true;
    },
    /**
     * 保存事件
     * 获取微信也会触发这个方法，并传参进来，其余情况不会传参进来
     */
    saveAddress(wechatAddress = 'false') {
      let params = {};
      // 地址编辑页保存地址
      if (wechatAddress === 'false') {
        params = {
          receiver: this.address.receiver, // 收件人
          phone: this.address.phone, // 手机号码
          province: this.address.province, // 省
          currentArea: this.currentArea,  // 区号
          city: this.address.city, // 市
          county: this.address.county, //区/县
          detail: this.address.detail, // 详细地址
          is_default: this.isdefault ? 1 : 0, // 是否设为默地址,
          id: this.address.id || null,
        };
      } else {
        // 获取微信地址并保存
        params = {
          receiver: wechatAddress.userName, // 收件人
          phone: wechatAddress.telNumber, // 手机号码
          currentArea: this.currentArea,  // 区号
          province: wechatAddress.provinceName, // 省
          city: wechatAddress.cityName, // 市
          county: wechatAddress.countryName, //区/县
          detail: wechatAddress.detailInfo, // 详细地址
          is_default: 1, // 是否设为默地址,
        };
      }
      // 防止短时间重复点击
      if (!this.saveButtonEnabled) {
        return;
      }
      let flag = this.checkValue(this.dataArray);
      // flag可能为其他内容，必须判断boolean值
      if (flag !== true) {
        Toast(flag);
        return;
      } else {
        this.saveButtonEnabled = false;
        const isAdd = this.isNew || wechatAddress != 'false';
        const request = isAdd ? addressAdd : addressEdit;
        request(params).then(data => {
          const obj = {
            type: isAdd ? ADDRESS_HANDLE.ADD : ADDRESS_HANDLE.EDIT,
            addressInfo: {
              ...params,
              ...data,
            },
          }
          this.$emit('handleAddressCallback', obj);
          Toast(this.t('save_suc'))
        }).catch((err) => {
          console.log(err);
        }).finally(() => {
          this.saveButtonEnabled = true
        });
      }
    },
    // 删除地址
    deleteAddress() {
      Dialog.confirm({
        title: this.t('addressSelect_delete_address'),
        getContainer: '#address'
      })
        .then(() => {
          addressDelete({
            id: this.address.id,
          }).then(() => {
            if (this.addressInfo.id === this.address.id) {
              this.$emit('handleAddressCallback', {
                type: ADDRESS_HANDLE.DELETE
              });
            }
            this.$emit('onClick');
            Toast(this.t('deleted_successfully'))
          })
        })
    },
    //电话输入优化
    limitInput(value) {
      return value.replace(/[^\d]/g, "");
    },
    // 所有输入框校验
    checkValue(val) {
      let flag = true;
      for (let item of val) {
        switch (item.key) {
          case "receiver":
            if (item.value || item.value.length > 0) {
              continue;
            } else {
              flag = this.t('fill_consignee_name');
              return flag;
            }
          case "phone":
            if (item.value || item.value.length > 0) {
              if (this.currentArea.nation_code != '86') {
                continue;
              } else {
                const patt = /^[1][3-9][\d]{9}/.test(item.value);
                if (item.value.length === 11 && patt) {
                  continue;
                } else {
                  flag = this.t('address_phone_num');
                  return flag;
                }
              }
            } else {
              flag = this.t('fill_phone_number');
              return flag;
            }
          case "area":
            if (item.value || item.value.length > 0) {
              continue;
            } else {
              flag = this.t('addressSelect_select_area');
              return flag;
            }
          case "detail":
            if (item.value || item.value.length > 0) {
              continue;
            } else {
              flag = this.t('addressSelect_fill_detailed_address');
              return flag;
            }
          default:
            break;
        }
      }
      return true;
    },
  },
};
</script>

<style lang="scss" scoped>
@import "../../assets/styles/global.scss";
@import "../../assets/styles/common.scss";
::v-deep .van-cell {
  padding: 0.32rem;
}

::v-deep .van-field__label {
  width: 1.44rem;
  color: #666666;
}

::v-deep .van-cascader__title {
  // font-size: 0.32rem;
  font-weight: 500;
}

.edit-cont {
  overflow-y: auto;
  padding-bottom: 1.12rem;

  ::v-deep .van-overlay {
    // z-index: 2099 !important;
  }

  ::v-deep .van-dialog {
    z-index: 2100 !important;
  }
}

.input-wrapper {
  background: white;

  .phone-cont {
    display: flex;
    align-items: center;
    border-bottom: 1px solid rgb(245, 246, 247);
    width: calc(100% - 0.64rem);
    margin-left: 0.32rem;

    .phone-left {
      display: flex;

      .phone-title {
        display: block;
        width: 1.44rem;
        font-size: 0.28rem;
      }
    }

    .areaCode-content {
      padding-left: 0.24rem;
    }

    .phone-detail {
      position: relative;
      flex: 1;

      .phone-text {
        padding-left: 0.24rem !important;
      }

      .van-cell::after {
        border-bottom: none;
      }

      .error-phone {
        text-align: right;
        color: red;
        font-size: 0.24rem;
        position: absolute;
        left: 0.32rem;
        bottom: 0;
        width: fit-content;
      }
    }

    .phone-obtain {
      color: #1472FF;
      font-size: 0.28rem;
      font-weight: 600;
    }
  }

  .error-phone {
    border-bottom: 1px solid #FF4747;
  }

  .input-bar {
    position: relative;
    display: flex;
    align-items: center;
    padding: 0.32rem 0;

    i {
      position: absolute;
      right: 0;
      top: 50%;
      transform: translateY(-50%);
    }

    .input-title {
      width: 1.44rem;
      text-align: left;
    }

    .input:focus {
      outline: none;
    }

    .input::placeholder {
      color: #b2b2b2;
    }

    .input {
      width: 5rem;
      font-size: 0.28rem;
      box-shadow: 0px 0px 0px rgba(0, 0, 0, 0);
      -webkit-appearance: none;
      padding-left: 0.16rem;
    }

    .input.invalid {
      color: #ff4c51;
    }
  }

  .address-detail {
    position: relative;

    .detail-error {
      position: absolute;
      left: 2rem;
      bottom: 0.06rem;
      color: red;
      font-size: 0.24rem;
    }
  }
}

.default-wrapper {
  margin-top: 0.16rem;
  height: 1.12rem;
  padding: 0 0.32rem;
  box-sizing: border-box;
  background: white;
  display: flex;
  align-items: center;
  justify-content: space-between;
  color: rgba(102, 102, 102, 1);
  font-size: 0.28rem;
}

.finish-btn {
  box-sizing: border-box;
  border-top: 0.02rem solid #eee;
  position: fixed;
  bottom: 0;
  left: 0;
  background: #fff;
  width: 100%;

  .finish-btn-wrapper {
    padding: 0.16rem 0.28rem;
  }

  .finish {
    padding: 0.2rem 0;
    border-radius: 0.4rem;
    text-align: center;
    background: #09bb07;
    color: white;

    &.disabled {
      cursor: not-allowed;
      opacity: 0.5;
    }
  }

  .finish-double {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .cancel-btn {
      text-align: center;
      width: 2.12rem;
      padding: 0.16rem 0;
      margin-right: 0.24rem;
      background: rgba(255, 255, 255, 1);
      border-radius: 0.4rem;
      border: 0.02rem solid rgba(183, 183, 183, 1);
    }

    .finish2 {
      width: 4.5rem;
      padding: 0.2rem 0;
      border-radius: 0.4rem;
      text-align: center;
      color: #fff;

      &.disabled {
        cursor: not-allowed;
        opacity: 0.5;
      }
    }
  }
}

.input-border {
  border-top: 0.02rem solid #f5f5f5;
}

.icon-tiaozhuan {
  color: #d8d8d8;
  font-size: 0.4rem;
}

.van-popup--bottom {
  @include fixPosition;
  padding-bottom: 1.28rem;
}

</style>
